// var superagent = require('superagent');
// var cheerio = require('cheerio');

function getWeiXinHtml(webUrl = "https://mp.weixin.qq.com/s/Dc9h48oNsh82I760U1OdYg") {
  return new Promise((resolve, reject) => {
    superagent.get(webUrl).end(function (err, sres) {
      let result = {}, contentItems = [];
      if (err) reject(err)
      if (!sres.text) reject("解析错误，请重试！")
      let $ = cheerio.load(sres.text);
      $('div.rich_media_content').children().each(function (i, e) {
        //测试代码
        let content = {}, mText = $(this).text()
        if (mText) {
          let code = $(this).find('code')
          if (code && code.length) content.code = mText
          else content.text = mText
        } else {
          let image = $(this).find('img')
          image.length && image.each(function (imgIdx, imgEle) {
            let imageSrc = $(this).attr('data-src')
            imageSrc = imageSrc && imageSrc.replace('https:', 'https://images.weserv.nl/?url=https:')
            content.image = imageSrc && `${imageSrc}&wxfrom=5&wx_lazy=1&wx_co=1`
          })
        }
        if (content.text || content.image || content.code) contentItems.push(content)
      });
      result.content = contentItems
      return resolve(result)
    })
  })
}

module.exports = {
  getWeiXinHtml
}
